#!/bin/bash

# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ROOT_DIR=`pwd`
BUILD_DIR=`pwd`/ohos_sdl2
OUTPUT_DIR=`pwd`/sdl_output

OHOS_SDK=$ROOT_DIR/ohos-sdk/linux
CMAKE_DIR=$ROOT_DIR/cmake-3.26.4-linux-x86_64

ARCHS=("armeabi-v7a" "arm64-v8a")

function check_prepare () {
    if [ ! -d $OHOS_SDK ]
    then
        echo "sdk not ready ##############"
        return 1
    fi
    export OHOS_SDK=$OHOS_SDK

    if [ ! -d $CMAKE_DIR ]
    then
        echo "cmake not ready ##############"
        return 1
    fi
    export PATH=$CMAKE_DIR/bin:$PATH
    cmake --version

    return 0
}

function start_build() {
    local result=0
    cd $BUILD_DIR
    
    for arch in ${ARCHS[@]}
    do
        mkdir ${arch}-build
        ${OHOS_SDK}/native/build-tools/cmake/bin/cmake -LH -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_SKIP_RPATH=ON -DCMAKE_SKIP_INSTALL_RPATH=ON \
        -DCMAKE_TOOLCHAIN_FILE=${OHOS_SDK}/native/build/cmake/ohos.toolchain.cmake \
        -DCMAKE_INSTALL_PREFIX=${OUTPUT_DIR}/${arch} \
        -DOHOS_ARCH=${arch} \
        -DSDL_WAYLAND=OFF \
        -DSDL_WAYLAND_QT_TOUCH=OFF \
        -DSDL_TESTS=ON \
        -B${arch}-build -S./

        make VERBOSE=1 -C ${arch}-build/
        make install -C ${arch}-build/
        result=$?
        if [ $result -ne 0 ]
        then
            echo "make ${arch} failed!"
            break
        fi
    done
    
    cd $ROOT_DIR
    return $result
}

function start_compile() {
    check_prepare
    if [ $? -ne 0 ]
    then
        echo "check prepare failed!"
        return 1
    fi
    
    start_build
    if [ $? -ne 0 ]
    then
        echo "build SDL failed! ######################"
        return 1
    fi

    echo "build SDL SUCCESS!! ####################"
    return 0
}

start_compile $@

exit $?

#eof
